<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="searchFormRef" :model="queryParam" :inline="true">
        <el-form-item label="部门名称" prop="keywords">
          <el-input v-model="queryParam.keywords" placeholder="部门名称关键字" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="部门状态" prop="enabled">
          <el-select v-model="queryParam.enabled" placeholder="全部" clearable class="!w-[100px]">
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery"> <i-ep-refresh />重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button v-hasPerm="['dept:add']" type="success" @click="handleOpenAddDialog()"><i-ep-plus />新增</el-button>
        <el-button v-hasPerm="['dept:del']" type="danger" :disabled="selectionIds.length === 0"
          @click="handleDelete()"><i-ep-delete />删除
        </el-button>
      </template>

      <el-table v-loading="loading" :data="deptData" row-key="dept_id" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="部门名称" min-width="200" />
        <el-table-column prop="code" label="部门编号" width="200" />
        <el-table-column prop="enabled" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="100" />

        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button v-hasPerm="['dept:add']" type="primary" link size="small"
              @click.stop="handleOpenAddDialog(scope.row)"><i-ep-plus />新增
            </el-button>
            <el-button v-hasPerm="['dept:edit']" type="primary" link size="small"
              @click.stop="handleOpenEditDialog(scope.row)"><i-ep-edit />编辑
            </el-button>
            <el-button v-hasPerm="['dept:del']" type="danger" link size="small"
              @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--表单数据-->
    <Form ref="deptFormRef" v-model="dialog.visible" :title="dialog.title" :dept-item="selectedItem"
      @close="handleCloseDialog" @submit="handleDialogSubmit" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dept",
  inheritAttrs: false,
})

import DeptAPI, { DeptVO, DeptQuery } from "@/api/dept"
import { buildTree } from "@/utils";
import Form from "./form.vue";

const searchFormRef = ref(ElForm)

const loading = ref(false)
const dialog = reactive({
  title: "新增",
  visible: false,
})
const selectionIds = ref<number[]>([])

const selectedItem = ref<DeptVO>()

const queryParam = reactive<DeptQuery>({})

const deptData = ref<DeptVO[]>()

const getDeptTree = (queryCondition: QueryCondition = {}) => {
  loading.value = true
  DeptAPI.query().then((res) => {
    if (res.status == 200) {
      deptData.value = buildTree(res.data, 'dept_id', 'pid')
    }
  }).finally(() => { loading.value = false })
}


/** 查询部门 */
const handleQuery = () => {
  const queryCondition: QueryCondition = {}
  if (queryParam.keywords) {
    queryCondition.and?.push({ field: 'name', op: 'like', value: `%${queryParam.keywords}%` })
  }
  if (queryParam.enabled) {
    queryCondition.and?.push({ field: 'enabled', op: 'enabled', value: queryParam.enabled })
  }
  getDeptTree(queryCondition)
}

/** 重置查询 */
const handleResetQuery = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  handleQuery()
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  selectionIds.value = selection.map((item: any) => item.dept_id)
}

/**
 * 打开新增部门弹窗
 *
 */
const handleOpenAddDialog = (row: DeptVO = {}) => {
  dialog.title = "新增部门"
  if (row.dept_id) {
    selectedItem.value = {
      pid: row.dept_id
    }
  }
  dialog.visible = true
}
/**
 * 打开编辑部门弹窗
 */
const handleOpenEditDialog = (row: DeptVO = {}) => {
  dialog.title = "修改部门"
  selectedItem.value = Object.assign({}, row)
  dialog.visible = true
}


// 删除菜单
const handleDelete = (deptId?: number) => {
  const deptIds = deptId ? [deptId] : selectionIds.value
  if (!deptIds) {
    ElMessage.warning("请勾选删除项")
    return
  }
  ElMessageBox.confirm("确认删除已选中的部门及其子部门么?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    const deleteCondition: QueryCondition = {
      "_cond": { and: [{ field: "dept_id", op: "in", value: deptIds }] }
    }
    DeptAPI.deleteByCondition(deleteCondition).then((res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功")
        handleQuery()
      }
    }).finally(() => {
      loading.value = false
    })
  })
}

/** 提交部门表单 */
const handleDialogSubmit = () => {
  dialog.visible = false
  handleQuery()
}

/** 关闭弹窗 */
const handleCloseDialog = () => {
  dialog.visible = false
  handleQuery()
}

onMounted(() => {
  handleQuery()
})
</script>
